﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using LM.YF.K3Cloud.Plugin.Models;
using System;
using System.ComponentModel;

namespace LM.YF.K3Cloud.Plugin
{
    /// <summary>
    /// 货运单-计算并反写发货通知单的暂估运费
    /// <author>鹿奔</author>
    /// <date>240118</date>
    /// </summary>
    [HotUpdate, Description("计算并反写发货通知单的暂估运费（操作服务插件）")]
    public class CalcEstimatedFreightOperationServicePlugin : AbstractOperationServicePlugIn
    {
        #region 字段配置

        /// <summary>
        /// 明细-重量占比
        /// </summary>
        internal readonly ElementKeySchema F_RDLV_WeightRate = new ElementKeySchema
        {
            DbKey = "F_RDLV_WEIGHTRATE",
            FormKey = "F_RDLV_WeightRate",
            OrmKey = "F_RDLV_WeightRate"
        };

        /// <summary>
        /// 明细-总运费
        /// </summary>
        internal readonly ElementKeySchema F_RDLV_RowAmt = new ElementKeySchema
        {
            DbKey = "F_RDLV_ROWAMT",
            FormKey = "F_RDLV_RowAmt",
            OrmKey = "F_RDLV_RowAmt"
        };

        /// <summary>
        /// 通知单号
        /// </summary>
        internal readonly ElementKeySchema F_RDLV_NoticeNo = new ElementKeySchema
        {
            DbKey = "F_RDLV_NOTICENO",
            FormKey = "F_RDLV_NoticeNo",
            OrmKey = "F_RDLV_NoticeNo"
        };

        /// <summary>
        /// 产品编码
        /// </summary>
        internal readonly ElementKeySchema F_RDLV_Material = new ElementKeySchema
        {
            DbKey = "F_RDLV_MATERIAL",
            FormKey = "F_RDLV_Material",
            OrmKey = "F_RDLV_Material"
        };

        /// <summary>
        /// 单据体
        /// </summary>
        internal readonly ElementKeySchema FEntity = new ElementKeySchema
        {
            DbKey = "RDLV_t_DiliveOrdEntry",
            FormKey = "FEntity",
            OrmKey = "FEntity"
        };

        /// <summary>
        /// 单据体-源单分录ID
        /// </summary>
        readonly ElementKeySchema F_RDLV_SourceEntryID = new ElementKeySchema
        {
            DbKey = "F_RDLV_SourceEntryID",
            FormKey = "F_RDLV_SOURCEENTRYID",
            OrmKey = "F_RDLV_SourceEntryID"
        };

        #endregion

        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            e.FieldKeys.Add(F_RDLV_WeightRate.FormKey);
            e.FieldKeys.Add(F_RDLV_RowAmt.FormKey);
            e.FieldKeys.Add(F_RDLV_NoticeNo.FormKey);
            e.FieldKeys.Add(F_RDLV_Material.FormKey);
        }

        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            if (FormOperation.OperationId == Kingdee.BOS.Core.Metadata.FormElement.FormOperation.Operation_Save)
            {
                CalcFreight(e);
            }
        }

        private void CalcFreight(AfterExecuteOperationTransaction e)
        {
            var rows = e.SelectedRows;
            foreach (var row in rows)
            {
                var entries = row.DataEntity[FEntity.FormKey] as DynamicObjectCollection;
                for (int i = 0, l = entries.Count; i < l; i++)
                {
                    // 获取货运单分录数据
                    var entry = entries[i];
                    //var noticeNo = entry[F_RDLV_NoticeNo.OrmKey]?.ToString();
                    //var materialId = Convert.ToInt32((entry[F_RDLV_Material.OrmKey] as DynamicObject)?["Id"]);
                    var freight = Convert.ToDecimal(entry[F_RDLV_RowAmt.OrmKey]);
                    //var weightRate = Convert.ToSingle(entry[F_RDLV_WeightRate.OrmKey]);
                    //// 根据运费占比计算总运费
                    //var freightSum = weightRate == 0 ? 0 : (freight / weightRate);
                    // 获取发货通知单分录ID
                    //var noticeEntryId = DBUtils.ExecuteScalar(Context, $@"select FENTRYID
                    //    from T_SAL_DELIVERYNOTICEENTRY-- 发货通知单分录
                    //    where FID = (
                    //        select FID
                    //        from T_SAL_DELIVERYNOTICE
                    //        where FBILLNO = '{noticeNo}'
                    //    ) and FMATERIALID = {materialId};", 0);
                    var noticeEntryId = entry[F_RDLV_SourceEntryID.OrmKey]?.ToString();
                    /*
                        set F_ESTIMATED_FREIGHT = case
                            when F_ESTIMATED_FREIGHT + {freight} < {freightSum} then F_ESTIMATED_FREIGHT + {freight}
                            else {freightSum}
                        end
                     */
                    DBUtils.Execute(Context, $@"update T_SAL_DELIVERYNOTICEENTRY
                        set F_ESTIMATED_FREIGHT = {freight}-- 暂估运费
                        where FENTRYID = {noticeEntryId};");
                }
            }
        }
    }
}
